package org.will.jms;

import org.jdom2.CDATA;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by EdifierWill on 2016/8/10.
 */
public class OperationFactory {

    public static Operation create(String oprationXml)
    {
         return parseXmlToOperation(oprationXml);
    }

    @SuppressWarnings("unchecked")
    private static Operation parseXmlToOperation(String xml){
        Operation operation = new Operation();
        try {
            StringReader read = new StringReader(xml);
            InputSource source = new InputSource(read);
            SAXBuilder sb = new SAXBuilder();

            Document doc = sb.build(source);
            Element root = doc.getRootElement();

            operation.setTable(root.getAttribute("table").getValue());
            operation.setType(root.getAttribute("type").getValue());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dateTs = sdf.parse(root.getAttribute("ts").getValue());
            operation.setTs(dateTs);
            operation.setNumCols(root.getAttribute("numCols").getIntValue());

            Map<String,OperationCol> cols = new HashMap<>();
            for(Content content:root.getContent()){
                if(content.getClass().equals(Element.class)){
                    Element element = (Element)content;

                    OperationCol col = new OperationCol();
                    col.setName(element.getAttribute("name").getValue());
                    col.setIndex(element.getAttribute("index").getIntValue());

                    for(Content childContent:element.getContent()){
                        if(childContent.getClass().equals(Element.class)){
                            for(Content ccContent:((Element)childContent).getContent()){
                                if(ccContent.getClass().equals(CDATA.class)){
                                    if(((Element)childContent).getName().equals("before")){
                                        col.setBeforeValue(ccContent.getValue());
                                    }
                                    if(((Element)childContent).getName().equals("after")){
                                        col.setAfterValue(ccContent.getValue());
                                    }
                                }
                            }
                        }
                    }
                    cols.put(col.getName(),col);
                }
            }
            operation.setCols(cols);
            operation.getTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return operation;
    }
}
